// ignore_for_file: unused_local_variable
import 'dart:async';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import '../../app_views.dart';
import '../../core/utils/validators.dart';
import 'package:dio/dio.dart';
import 'auth_state.dart';

/// 认证逻辑控制器 - Authentication Logic Controller
///
/// 管理用户登录、注册、验证码等认证相关的业务逻辑
/// Manages authentication business logic including login, register, verification codes
class AuthLogic extends GetxController {
  final Rx<AuthState> state = AuthState().obs;
  // 使用新的API仓库层 - Use new API repository layer
  late final ApiRepository _apiRepository;

  Timer? _smsTimer;
  Timer? _emailTimer;

  @override
  void onInit() {
    super.onInit();
    _apiRepository = ApiRepository();
    _checkLoginStatus();
  }

  /// 检查登录状态 - Check login status
  void _checkLoginStatus() {
    final token = StorageService.to.token;
    state.value.isLoggedIn = token != null && token.isNotEmpty;
  }

  @override
  void onClose() {
    _smsTimer?.cancel();
    _emailTimer?.cancel();
    clearAllInputs(); // 页面关闭时清空
    super.onClose();
  }

  void toggleLoginMode(bool isSmsLogin) {
    // 切换时不清空输入内容，只清空错误信息
    state.value.isSmsLogin = isSmsLogin;
  }

  /// 清空所有输入
  void clearAllInputs() {
    // 重置为初始状态 - Reset to initial state
    state.value.phone = '';
    state.value.phoneSmsCode = '';
    state.value.phonePassword = '';
    state.value.phoneError = null;
    state.value.phoneSmsError = null;
    state.value.phonePasswordError = null;
    state.value.phoneSmsCountdown = 0;
    state.value.email = '';
    state.value.emailCode = '';
    state.value.emailPassword = '';
    state.value.emailError = null;
    state.value.emailCodeError = null;
    state.value.emailPasswordError = null;
    state.value.emailCountdown = 0;
    state.value.isSmsLogin = true;
    state.value.agreeTerms = false;
    state.value.errorMessage = null;
    state.value.isLoading = false;
    state.value.isLoggedIn = false;
  }

  // 手机相关输入
  void onPhoneChanged(String value) {
    state.value.phone = value;
    state.value.phoneError = Validators.validatePhone(value);
  }

  void onPhoneSmsCodeChanged(String value) {
    state.value.phoneSmsCode = value;
    state.value.phoneSmsError = Validators.validateSmsCode(value);
  }

  void onPhonePasswordChanged(String value) {
    state.value.phonePassword = value;
    state.value.phonePasswordError = Validators.validatePassword(value);
  }

  // 邮箱相关输入
  void onEmailChanged(String value) {
    state.value.email = value;
    state.value.emailError = Validators.validateEmail(value);
  }

  void onEmailCodeChanged(String value) {
    state.value.emailCode = value;
    state.value.emailCodeError = Validators.validateSmsCode(value);
  }

  void onEmailPasswordChanged(String value) {
    state.value.phonePassword = value;
    state.value.phonePasswordError = Validators.validatePassword(value);
    state.value.emailPassword = value;
    state.value.emailPasswordError = Validators.validatePassword(value);
  }

  void onAgreeTermsChanged(bool value) {
    state.value.agreeTerms = value;
    state.value.errorMessage = null;
  }

  // 倒计时
  void _startSmsCountdown() {
    _smsTimer?.cancel();
    state.value.phoneSmsCountdown = 60;

    _smsTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      final current = state.value.phoneSmsCountdown;
      if (current <= 1) {
        timer.cancel();
        state.value.phoneSmsCountdown = 0;
      } else {
        state.value.phoneSmsCountdown = current - 1;
      }
    });
  }

  void _startEmailCountdown() {
    _emailTimer?.cancel();
    state.value.emailCountdown = 60;

    _emailTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      final current = state.value.emailCountdown;
      if (current <= 1) {
        timer.cancel();
        state.value.emailCountdown = 0;
      } else {
        state.value.emailCountdown = current - 1;
      }
    });
  }

  // 验证码请求
  /// 请求短信验证码 - Request SMS verification code
  /// 使用API仓库层发送短信验证码请求
  Future<void> requestSmsCode() async {
    if (!_validatePhone()) return;

    try {
      state.value.isLoading = true;

      // 使用API仓库层请求短信验证码 - Use API repository to request SMS code
      final response = await _apiRepository.requestSmsCode(state.value.phone);

      if (response.success) {
        _startSmsCountdown();
        Get.snackbar(
          '发送成功',
          '验证码已发送到您的手机',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.green,
          colorText: Colors.white,
        );
      } else {
        state.value.phoneSmsError = response.message ?? '发送失败，请重试';
      }
    } catch (e) {
      state.value.phoneSmsError = '网络异常，请检查网络连接';
      debugPrint('请求短信验证码失败: $e');
    } finally {
      state.value.isLoading = false;
    }
  }

  /// 请求邮箱验证码 - Request email verification code
  /// 使用API仓库层发送邮箱验证码请求
  Future<void> requestEmailCode() async {
    if (!_validateEmail()) return;

    try {
      state.value.isLoading = true;

      // 使用API仓库层请求邮箱验证码 - Use API repository to request email code
      final response = await _apiRepository.requestEmailCode(state.value.email);

      if (response.success) {
        _startEmailCountdown();
        Get.snackbar(
          '发送成功',
          '验证码已发送到您的邮箱',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.green,
          colorText: Colors.white,
        );
      } else {
        state.value.emailCodeError = response.message ?? '发送失败，请重试';
      }
    } catch (e) {
      state.value.emailCodeError = '网络异常，请检查网络连接';
      debugPrint('请求邮箱验证码失败: $e');
    } finally {
      state.value.isLoading = false;
    }
  }

  bool _validatePhone() {
    final phoneErr = Validators.validatePhone(state.value.phone);
    state.value.phoneError = phoneErr;
    return phoneErr == null;
  }

  bool _validateEmail() {
    final emailErr = Validators.validateEmail(state.value.email);
    state.value.emailError = emailErr;
    return emailErr == null;
  }

  // 登录验证
  bool _validateSmsLogin() {
    if (!state.value.agreeTerms) {
      state.value.errorMessage = '请先阅读并同意用户协议';
      return false;
    }

    final phoneErr = Validators.validatePhone(state.value.phone);
    final codeErr = Validators.validateSmsCode(state.value.phoneSmsCode);
    final pwdErr = Validators.validatePassword(state.value.phonePassword);

    state.value.phoneError = phoneErr;
    state.value.phoneSmsError = codeErr;
    state.value.phonePasswordError = pwdErr;

    return phoneErr == null && codeErr == null && pwdErr == null;
  }

  bool _validateEmailLogin() {
    final emailErr = Validators.validateEmail(state.value.email);
    final codeErr = Validators.validateSmsCode(state.value.emailCode);
    final pwdErr = Validators.validatePassword(state.value.emailPassword);

    state.value.emailError = emailErr;
    state.value.emailCodeError = codeErr;
    state.value.emailPasswordError = pwdErr;

    return emailErr == null && codeErr == null && pwdErr == null;
  }

  // 注册验证
  bool _validateSmsRegister() {
    if (!state.value.agreeTerms) {
      state.value.errorMessage = '请先阅读并同意用户协议';
      return false;
    }

    final phoneErr = Validators.validatePhone(state.value.phone);
    final codeErr = Validators.validateSmsCode(state.value.phoneSmsCode);
    final pwdErr = Validators.validatePassword(state.value.phonePassword);

    state.value.phoneError = phoneErr;
    state.value.phoneSmsError = codeErr;
    state.value.phonePasswordError = pwdErr;

    return phoneErr == null && codeErr == null && pwdErr == null;
  }

  bool _validateEmailRegister() {
    final emailErr = Validators.validateEmail(state.value.email);
    final codeErr = Validators.validateSmsCode(state.value.emailCode);
    final pwdErr = Validators.validatePassword(state.value.emailPassword);

    state.value.emailError = emailErr;
    state.value.emailCodeError = codeErr;
    state.value.emailPasswordError = pwdErr;

    return emailErr == null && codeErr == null && pwdErr == null;
  }

  /// 登录 - Login
  /// 根据当前登录模式执行相应的登录逻辑
  /// Executes corresponding login logic based on current login mode
  Future<void> login() async {
    // 验证输入 - Validate input
    final isValid =
        state.value.isSmsLogin ? _validateSmsLogin() : _validateEmailLogin();
    if (!isValid) return;

    try {
      state.value.errorMessage = null;
    state.value.isLoading = true;

      BaseResponse<AuthUser> result;

      if (state.value.isSmsLogin) {
        // 手机登录 - Phone login
        final loginRequest = LoginRequest(
          phone: state.value.phone,
          smsCode: state.value.phoneSmsCode,
          password: state.value.phonePassword,
        );
        result = await _apiRepository.login(loginRequest);
      } else {
        // 邮箱登录 - Email login
        final loginRequest = LoginRequest(
          email: state.value.email,
          smsCode: state.value.emailCode,
          password: state.value.emailPassword,
        );
        result = await _apiRepository.login(loginRequest);
      }

      if (result.success && result.data != null) {
        // 登录成功，保存用户信息 - Login successful, save user info
        final userData = result.data!.toJson();
        await _saveUserData(userData);

        // 跳转到主页 - Navigate to home
        Get.offAllNamed('/root');

        Get.snackbar(
          '登录成功',
          '欢迎回来！',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.green,
          colorText: Colors.white,
        );
      } else {
        state.value.errorMessage = result.message ?? '登录失败';
      }
    } catch (e) {
      debugPrint('登录失败: $e');

      String errorMessage;
      if (e is DioException) {
        switch (e.type) {
          case DioExceptionType.connectionTimeout:
          case DioExceptionType.sendTimeout:
          case DioExceptionType.receiveTimeout:
            errorMessage = '网络连接超时，请检查网络设置';
            break;
          case DioExceptionType.badResponse:
            errorMessage = '服务器响应错误，请稍后重试';
            break;
          case DioExceptionType.cancel:
            errorMessage = '请求已取消';
            break;
          case DioExceptionType.unknown:
          default:
            errorMessage = '网络连接失败，请检查网络设置';
            break;
        }
      } else {
        errorMessage = '登录失败，请稍后重试';
      }

      state.value.errorMessage = errorMessage;
    } finally {
      state.value.isLoading = false;
    }
  }

  /// 注册 - Register
  /// 根据当前登录模式执行相应的注册逻辑
  /// Executes corresponding register logic based on current login mode
  Future<void> register() async {
    // 验证输入 - Validate input
    final isValid = state.value.isSmsLogin
        ? _validateSmsRegister()
        : _validateEmailRegister();
    if (!isValid) return;

    try {
      state.value.errorMessage = null;
    state.value.isLoading = true;

      BaseResponse<AuthUser> result;

      if (state.value.isSmsLogin) {
        // 手机注册 - Phone register
        final registerRequest = RegisterRequest(
          phone: state.value.phone,
          smsCode: state.value.phoneSmsCode,
          password: state.value.phonePassword,
        );
        result = await _apiRepository.register(registerRequest);
      } else {
        // 邮箱注册 - Email register
        final registerRequest = RegisterRequest(
          email: state.value.email,
          emailCode: state.value.emailCode,
          password: state.value.emailPassword,
        );
        result = await _apiRepository.register(registerRequest);
      }

      if (result.success && result.data != null) {
        // 注册成功，保存用户信息 - Register successful, save user info
        final userData = result.data!.toJson();
        await _saveUserData(userData);

        // 跳转到主页 - Navigate to home
        Get.offAllNamed('/root');

        Get.snackbar(
          '注册成功',
          '欢迎加入我们！',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.green,
          colorText: Colors.white,
        );
      } else {
        state.value.errorMessage = result.message ?? '注册失败';
      }
    } catch (e) {
      state.value.errorMessage = e.toString();
      debugPrint('注册失败: $e');
    } finally {
      state.value.isLoading = false;
    }
  }

  /// 保存用户数据 - Save user data
  /// 将登录/注册成功后的用户数据保存到本地存储
  /// Saves user data to local storage after successful login/register
  Future<void> _saveUserData(Map<String, dynamic> userData) async {
    try {
      // 保存token - Save token
      if (userData['token'] != null) {
        await StorageService.to.setToken(userData['token']);
      }

      // 保存用户基本信息 - Save basic user info
      await StorageService.to.saveUser(
        id: userData['id']?.toString(),
        phone: userData['phone']?.toString(),
        email: userData['email']?.toString(),
      );

      // 更新登录状态 - Update login status
      state.value.isLoggedIn = true;
    } catch (e) {
      debugPrint('保存用户数据失败: $e');
    }
  }
}
